<?php
namespace app\common\service\message\recharge;
use app\common\model\Setting as SettingModel;
use app\common\service\message\Basics;

/**
 *  用户充值消息通知
 * Class Account
 * @package app\common\service\message\recharge
 */
class Account extends Basics
{
    /**
     * 参数列表
     * @var array
     */
    protected $param = [
        'order' => [],         // 拼单详情
    ];

    /**
     * 发送消息通知
     * @param array $param
     * @return mixed|void
     * @throws \think\Exception
     */
    public function send($param)
    {
        // 记录参数
        $this->param = $param;
        // 微信订阅消息通知用户
        $this->onSendWxSubMsg();
    }

    /**
     * 微信订阅消息通知用户
     * @return bool
     * @throws \app\common\exception\BaseException
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    private function onSendWxSubMsg()
    {
        file_put_contents("notify34.log", '储值订单'.json_encode( $this->param['order']).  "\n", FILE_APPEND);
        // 拼单详情
        $orderInfo = $this->param['order'];
        $wxappId = $orderInfo['wxapp_id'];

        // 获取订阅消息配置
        $template = SettingModel::getItem('submsg', $wxappId)['recharge']['account'];
        if (empty($template['template_id'])) {
            return false;
        }
        file_put_contents("notify34.log", '储值订单类型'.json_encode($orderInfo).  "\n", FILE_APPEND);
        // 发送订阅消息
        return $this->sendWxSubMsg($wxappId, [
            'touser' => $orderInfo['user']['open_id'],
            'template_id' => $template['template_id'],
            'page' => "pages/vip/vip?order_id={$orderInfo['order_id']}",
            'data' => [
                // 充值门店名称
                $template['keywords'][0] => ['value' =>$this->getWaxppName($wxappId)],
                // 充值金额
                $template['keywords'][1] => ['value' => $orderInfo['pay_price']],
                // 充值时间
                //$template['keywords'][2] => ['value' =>format_time($orderInfo['pay_time'])],
                $template['keywords'][2] => ['value' =>$orderInfo['pay_time']['text']],
                // 账户余额
                $template['keywords'][3] => ['value' => $this->getUserMoney($orderInfo)],
            ]
        ]);
    }

    /**
     *  获取商户名称
     * @param $wxappId
     * @return bool|float|mixed|string|null
     */
   private function getWaxppName($wxappId){
        return db('wxapp')->where('wxapp_id',$wxappId)->value('wxapp_name');
   }

    /**
     *  获取用户储值余额
     * @param $order
     * @return bool|float|mixed|string|null
     */
   private function getUserMoney($order){
        return db('user')->where(['wxapp_id'=>$order['wxapp_id'],'user_id'=>$order['user_id']])->value('money');
   }

}